I have seen lots of questions in diffrent forums for adding items in drop down list or list box using javascript. Below is the script for the same.
<script type="text/javascript"> function AddItem(Text,Value) { // Create an Option object
var opt = document.createElement("option");
// Add an Option object to Drop Down/List Box document.getElementById("DropDownList").options.add(opt);
// Assign text and value to Option object opt.text = Text; opt.value = Value; }
<script />
You can use this function in for loop to add more than one item.
Happy Programming !!
yah its really nice solution…
that will help me in ajax application
Hi,
Please let me know about this issue:
I have a dropdown with the following options in it.
Select
New Category
abc
efg
and when the user selects new category he will be given by a text field to enter the calue for the new category; and the value entered by the user should be added in the dropdown list as the last time.
for eg: if user select new actegory and enters the value as “ghj” then this value should be the last item in the dropdown and it should lok something like:
Select
New Category
abc
efg
ghj
Please help me out with this.
Thanks,
zulfi
how to add value to drop down list box
do you know how to populate a dhtml select/option a hidden list? Thanks.
HI
UR code is good but when i m get the select the value is retuen 0 (first index value) but i need select value .
can u help me out.
Alok,
Do you wnat the selected value from sever side code or javascript?
hello.. thank you for this code. what if the selected value is from the database..
thanx ya..
hey i wasn’t able to add a new item to an existing combobox using java script..
could anyone please help me with that?
it’s not working in NETSCAPE.
Good One
Raj,
I have not checked this in Netscape. However it is working fine in IE, Firefox, Safari. Can you please let me know the error so that I can try to solve it?
very goood topic
goooooooooo!!!!!
Really thanx alot.
Thanks a lot. Its working fine.
dear
plz send me the code how to transfer multiple selected items from one listbox to another list box using javascript in asp.net 1.1.
plz also tell me how to implement add items to listbox or drop down list javascriptcode in asp.net
SRK,
This link will help you.
http://www.mattkruse.com/javascript/selectbox/index.html
Hi all,
I need to add items in listbox from child window from javascript. Here’s the code i m using:
var listDocUpload = window.opener.document.getElementById(“listDocUpload”);
var optn = document.createElement(“OPTION”);
optn.text = “Filename”;
optn.value = “filePath”;
listDocUpload.options.add(optn);
I am getting javacsript error when the optn is getting added to the listbox on the parent page.
Can someone help?..its kind of urgent
This solution does not work for me. Its giving me object required on following line of code:
document.getElementById(“lbEmp”).options.add(opt);
lbEmp is my .aspx listbox. Any clue?
Trushar,
Is lbEmp is ClientID for your dropdown list or List box? can you please check if you are able to find your contrl? Use following,
alert(document.getElementById(”lbEmp”));
Check whether it is [object] or undefined? May be you are not getting your control properly.
Hi Gargi,
same here, I am not able to add an option in combo box which is located in parent window.
Getting ‘Unknown Exception’ in the last line.
Could anyone advise me, how to add new option in parent window combo…
Thank in advance.
var cmbProjectManager = window.opener.document.getElementById(“cmbProjectManager”);
if(cmbProjectManager != null)
{
var optionValue = eid + “,” + email;
//var optionItem;
//optionItem = new Option( username, optionValue, false, false);
//cmbProjectManager.options[cmbProjectManager.length] = optionItem;
var optn;
optn = document.createElement(“OPTION”);
optn.text = username
optn.value = optionValue
cmbProjectManager.options.add(optn);
}
delete it all
Hi
Thanks for this code
i want to disable some items in the dropdown list.
Hi,
It’s not working in Firefox and it’s working in IE. Anyone knows to add the item in firefox????
Yespee,
I have tested this code in Firefox 2.0.0.6 and its working fine. Can you please let me know which error are you getting?
remove() is not working in firefox
I get tis error
ObjX.options.remove is not a function
[Break on this error] ObjX.options.remove(ObjX[i]);
Hi! All,
Please I really need your help. None Of theBlog onnet had really helped me out.
I need to avoid adding duplicate items between two Listbox. I don’t know how to go further. Though I’m Successful in transfering object from Listbox(i.e LstSourceObject) to the other ListBox (i.i LstDestinationObject) using Double click on item selected in LstSourceObject.
Here is my code:
sub LstSoureObject_ondblClick()
if document.getElementById(“LstSoureObject”).options(document.getElementById(“LstSoureObject”).selectedIndex).Text “” then
if trim(document.getElementById(“cmbGrpCode”).Value) “—Select—” and trim(document.getElementById(“CmbDashboard”).Value) “—Select—” then
Dim MyOption
Set MyOption = Document.createElement(“OPTION”)
document.getElementById(“LstDestinationObject”).Add MyOption
MyOption.innerText = document.getElementById(“LstSoureObject”).options(document.getElementById(“LstSoureObject”).selectedIndex).Text
MyOption.Value = “N” & document.getElementById(“LstSoureObject”).options(document.getElementById(“LstSoureObject”).selectedIndex).Value
End if
End if
End Sub
Please I really need help Urgently.
I’ll be really Thnakful to all If you can help me.
Waiting for the response.
thankx
Hi i used your code to add elements to my dropdown list its working perfectly in IE but the same is not working in firefox opera and safari can u please help me out in this issue ?
How to add opt group tag for listboxes in 508 compliance?
hi Chirag your blog is so nice. i want to delete item from a listbox without any button click as we select a item in listbox and press delete button in keyboard it will delete. how can i achive this?
present i am doing this in script with button click as
function RemoveDates()
{
var ListDates=document.getElementById(‘lsbDates’)
if(ListDates.selectedIndex != -1)
{
ListDates.remove(ListDates.selectedIndex)
}
}
thanks in advance
hi chirag,
i got the answer to my doubt
solution is
function operation(e)
{
var unicode=e.keyCode? e.keyCode : e.charCode
var ListDates=document.getElementById(‘ListBox2’)
if(ListDates.selectedIndex != -1 && unicode==46)
{
ListDates.remove(ListDates.selectedIndex)
}
}
add a attribute to listbox2 in page load
ListBox2.Attributes.Add(“OnKeyDown”, “operation(event)”)
that all.
thanks.
Brammam,
Thanks for providing us a solution that you had found. Thats really good piece of code.
Hi Chirag,
i use the code and it works fine but i have a trouble when i call the postback in my aspx form.
It seems a problem of Validation, when “loadPostData” is called by the server for the drop down list that i’ve fill.
Have you ever find this kind of problem?
Best regards, and thanks
Andrea
This code is not working 4 me. It is giving error at
document.getElementById(“qual”).options.add(opt);
line. This ismy code, plz help me once.
var opt = document.createElement(“B.Sc”);
opt.text = “B.Sc”;
opt.value = “B.Sc”;
document.getElementById(“qual”).options.add(opt);
Thankx
Hi Ramarao,
There is a error in first line of your code. You have written
var opt = document.createElement(”B.Sc”);.
Instead of this you should write
var opt = document.createElement(“option”);
This provided code works properly to populate data in combo thru javascript.
But the problem is, I m not able to retrieve selected data in code behind.
i.e., Consider, I have selected one of the items from this combo, & I want to fetch the SelectedItem.Value of the selected item. But its .SelectedIndex = 0; whereas I had selected one of the items whose .SelectedIndex > 0.
Why it is so?
Purnima,
Nice question. Let me explain you, when you fill the items in dropdown list using code behind your valus are stored in viewstate and during postback server loads these values from viewstate and you will get the selected value and selected index.
Now when you add a new item in dropdownlist using javascript this value is added from client side and thus will not stored in viewstate so server is not aware of (or have no idea) about new item. So during postback you will not get this value.
To get the selected value on code behind you need to store selected item from dropdownlist in to a hidden field before postback. You can either do it by calling a javascript function on “OnClientClick” event (or by registring javascript function in code behind using Button.Attributes.Add(“onclick”,”javascript function name”);) which get the selected value from dropdown and save it in hidden field.
document.getElementById(“Hidden Field Client ID”).value = document.getElementById(“Dropdownlist client ID”).options[document.getElementById(“Dropdownlist client ID”).selectedIndex].text;
OR
You can call this function on “onchange” event of dropdownlist.
I hope this has cleared you doubt and will help in solving your isue.
Thanks for ur reply.
The solution that you have provided is already known to me. I was looking for some better way out. But fine, for time being, I’ll go ahead with this one only [No other option 😦 ].
One more thing, in second para of your replay i.e.,
“Now when you add a new item in dropdownlist using javascript this value is added from client side and thus will not stored in viewstate so server is not aware of (or have no idea) about new item. So during postback you will not get this value.”;
Your comment from above para is wrong:
“thus will not stored in viewstate so server is not aware of (or have no idea) about new item.”
B’coz once I select an item from combo, it gets posted back to server and it should carry the selected value with itself as a part of request paramter.
By the way, thanks for the immediate reply.
Thanks.
hi
when i m get the select the value is retuen 0 injavacript but i cant reterive that value using that value in select comand
Hai friends Your explanations are very good, I need some help, for validating controls in a gridbox(Eg. TextBox)
Juno,
You can take appropriate validation control from available validation control and assing its ControlToValidate property to the name of textbox. This will work.
Hi Siva
You need to pass the value for optionValue as element.value or the text value you are using for the element.text. It will work
visit http://www.codepal.co.in
how to get the selected multiple listbox options in other page
Hi chiragrdarji,
I have a requirement like…
i need a listbox, if you enter any text in textbox, then by some event(onkeydown/up…..), the text you entered have to be added as an item in the listbox items.
without postbacks through Javascript.
I am new to javascript, so can u be clear in coding.
Manoj
Thanks for nice code, it helped me a lot.
How to add items to ASP.Net drop down list through client side VBScript
hey really fantastic……
Thanks a lot ………….
just wanted to find out if u can drag and drogfrom one listbox to another listbox using javascript if so could u help me out with it
function AddItem(Text,Value)
{
// Create an Option object var opt = document.createElement(“option”);
// Add an Option object to Drop Down/List Box
document.getElementById(“DropDownList”).options.add(opt); // Assign text and value to Option object
opt.text = Text;
opt.value = Value;
}
This code is fine…
my problem is what i have to write in belowline to call that function(AddItem)
I want to call that function in page_load only..
I mean i want many values while page is loading..
Please reply to my mail
thanks
haripinna@yahoo.com
hi
our aim is to do a autofill in a textfield using a ajax call in java script+struts…we are able to send a value from a value to action class and able to hit the data base and fetch the values and we are adding the values in a arraylist and now we are getting the response in the ajax call only…now we are able to get that array list values in java script…..the issue is …we are unable to set the values to the combo box..can u plz guide
Thanks for the code!
Hi,
Thanks for the code,
I tried it and had an error
Object does not support this property or method
on the document.CreateElement(“option”); line
I am also getting “Object does not support this property or method” error. For me it is on window.document.getElementById(“ctl00_lstContact”).options.add(opt);
How can i clear the HTML combo box using javascript….
#
ijay
hi
our aim is to do a autofill in a textfield using a ajax call in java script+struts…we are able to send a value from a value to action class and able to hit the data base and fetch the values and we are adding the values in a arraylist and now we are getting the response in the ajax call only…now we are able to get that array list values in java script…..the issue is …we are unable to set the values to the combo box..can u plz guide
#
on June 7, 2008 at 8:51 am49 jasper carpizo
Thanks for the code!
#
on June 8, 2008 at 11:31 am50 Augustine
Hi,
Thanks for the code,
I tried it and had an error
Object does not support this property or method
on the document.CreateElement(”option”); line
Leave a Reply
Name (required)
Mail (will not be published) (required)
WebsiteBlog at WordPress.com. | Theme: Mistylook by Sadish.
Thanks guys,
Smaller things do attribute to Bigger Results.
Regards
Noor
Hi Chiragrdarji
I am new to java programming & trying to learn the basics.I have one prob————-i want to populate a drop down box depending upon the selection of another drop down box.How this can be done—————–i had tried to find the answer in many of the forum but no one can give me the idea————–
Best regards, and thanks
Sankar
Sankar, if u want to populate a drop down box depending upon the selection of another drop down box, ur code will look something like this(assuming u r working with frames or windows):
………….
………….
………….
………….
JComboBox cb1=new JComboBox();
JComboBox cb2=new JComboBox();
cb1.addItem(“c1”);
cb1.addItem(“c2”);
cb1.addItem(“c3”);
add(cb1);
add(cb2);
String s1=(String)cb1.getSelectedItem();
if(s1.equals(“c1”))
{cb2.addItem(“a”);
cb2.addItem(“b”);
cb2.addItem(“c”);
}
else if(s1.equals(“c2”))
{cb2.addItem(“p”);
cb2.addItem(“q”);
cb2.addItem(“r”);
}
else if(s1.equals(“c3”))
{cb2.addItem(“x”);
cb2.addItem(“y”);
cb2.addItem(“z”);
}
………….
………….
………….
………….
i want to disable some items in the dropdown list.
Hi Deepak,
For ur Question the following is the Answer
Dropdown.item.isReadOnly();
isReadOnly is the Property which makes the items to Read Only
Hi Chirag & all,
here is my javascript:
if (xmlHttp.readyState==4 || xmlHttp.readyState==”complete”)
{
document.getElementById(‘CustomerDetails’).innerHTML=xmlHttp.responseText;
var opt = document.createElement(“option”);
document.getElementById(‘DropDownList2’).options.add(opt);
opt.text=xmlHttp.responseText;
//opt.text=”hi”;
//opt.value=”hh”;
//document.getElementById(‘DropDownList2’).addItem=xmlHttp.responseText;;
}
my ajax aspx.cs:
Response.Clear();
StringBuilder sb = new StringBuilder();
sb.Append(“”);
string provider = “Provider=Microsoft.Jet.OLEDB.4.0;”;
string db = “Data Source=C:\\Documents and Settings\\debasree.das\\Desktop\\EmployeeDetail.mdb”;
string connstr = provider + db;
string query = “SELECT * FROM EmpDetails WHERE EmpID = ?”;
OleDbConnection conn = new OleDbConnection(connstr);
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.AddWithValue(“”, Request.QueryString[“EmpID”]);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
for (int i = 1; i < 3; i++)
{
//sb.Append(dr[i].ToString()+”” );
//Response.Write(sb.ToString());
Response.Write(dr[i].ToString());
//sb.Append(dr[2].ToString() + “”);
}
}
dr.Close();
dr.Dispose();
conn.Close();
conn.Dispose();
it is supposed to return 2values to be populated in dropdown, as 2 options.
but it is showing like:
[for empID :111 it returns: Raj (name) & Delhi(city)]
RajDelhi ————- as a single option for the dropdown.
but i want, 2 options: Raj
Delhi
in the dropdown.
but, Response.Write(dr[i].ToString()); is returning “RajDelhi”.
please help me out.
thanx.
I am currently calling drop down list from Java script
but i have long strings and i cannot display them because my page will only show some space for the drop down ctrl
can any one give a soln for this to be able to show strings of long length /size
thanks in advance
Thanx Shimmer,
it’s really helpful————–but actually i want to do like this—-my first drodown list items are hardcoded in element but second dropdown list which will be populated by the selection of first dropdown list ,should contain data directly fetched from database.
How can this be possible———if u or anyone in the blog give some directions about this ——–it would be really helpful for me .
Thanx in advance
sankar
I want to add multiple incremented values generated using javascript to a dropdownlist using javascript
Thanx,
MDP
Thx man…worked for me…Very useful
I am programmer, but not a JavaScript programmer, and I am trying to modify our application which uses some JavaScript. My current issue is this: We have 2 listboxes that move names from left to right, and vice versa. The left hand box contains the names in various colours. The code works great for moving the items, but does not retain the color of the items it moved. The lines looks like:
The JavaScript is here:
function MoveBetweenListBoxes(lbFrom, lbTo, bAll, iMax) {
var FromBox = document.getElementById(lbFrom);
var ToBox = document.getElementById(lbTo);
var FromIndex = FromBox.options.selectedIndex
if(typeof(iMax) == ‘undefined’) {
iMax = 9999
}
var iLastIndex = 0
var iLbCounter = 0
if (FromIndex != -1) {
do {
if ((FromBox.options[iLbCounter].selected == true || bAll == true) && ToBox.options.length +1 <= iMax) {
var FromIndex = FromBox.options[iLbCounter]
var opt = new Option (FromBox.options[iLbCounter].text , FromBox.options[iLbCounter].value)
//ToBox.options[ToBox.options.length] = opt
ToBox.options.add(opt);
FromBox.options[iLbCounter]= null;
iLastIndex = iLbCounter
}
else{
iLbCounter = iLbCounter + 1}
}
while (iLbCounter <= FromBox.options.length -1 && ToBox.options.length +1 = 2){
FromBox.options[iLastIndex].selected = true}
}
So, is there a way to modify this to make it retain the color of the item it is moving? I thought maybe adding:
FromBox.options[iLbCounter].style would work, but doesn’t appear supported.
Any help is greatly appreciated.
Kent
PS: I’ve used your site before for other items….it is truly one of the most informative! Thanks for all.
very easy and straightforward answer
function AddItem(Text,Value)
{
// Create an Option object var opt = document.createElement(“option”);
// Add an Option object to Drop Down/List Box
document.getElementById(“DropDownList”).options.add(opt); // Assign text and value to Option object
opt.text = Text;
opt.value = Value;
}
This code is fine…
my problem is what i have to write in belowline to call that function(AddItem)
I want to call that function in page_load only..
I mean i want many values while page is loading..
Please reply to my mail
Hi,
I want to create a jsp page that has users populated from a database, when I click in a user two listboxes appear:
listAssignedRoles with assigned roles
listNoAssignedRoles the rest of roles not assigned yet
these two lists are populated from a the database.
I want when I move items between listboxes and hit submit button the database get updated too.
Please your help is appreciated.
thanks
how to add combox in items 1 to 10 using javascript
how to add items in dropdownlist using vb script
asdfasfasdfasdfasdf
its all bull shit!
How to assing dorpdown list values using innerHTML in javascript
i am having dropdown box on page if i keep blank then records are not dispalying in Grid but saving in database if i keep blank then it should keep blank in gridview and display other fields in grid its becouse of INNER JOIN,please give solution
Cheers Mate!
Hi Chiragrdarji…
i found the code u have given helpful
is it possible to add listitems from one dropdownlist (ddl1)to another(ddl2) list on clientside,
the listitems should be added to ddl2 when a listitem in the ddl1 is selected.and this should not require any postback to the server….
regards,
sv
Thank U
Hi need ur help in populating a listbox2 from another using javascript but after the page refreshes the items in the listbox2 vanishes
i think there is some concept of hidden field……….
so if any can help me out
Thanks in advance
nice code
add items dropdown how to call function pl reply my mail
function AddItem(Text,Value)
{
// Create an Option object var opt = document.createElement(“option”);
// Add an Option object to Drop Down/List Box
document.getElementById(“DropDownList”).options.add(opt); // Assign text and value to Option object
opt.text = Text;
opt.value = Value;
}
my problem is what i have to write in belowline to call that function(AddItem)
I want to call that function in page_load only..
I mean i want many values while page is loading..
Please reply to my mail
hello ,
I have done same thing in C#, everything is running well
But when I post my form for submission I got the error
Invalid postback or callback argument. Event validation is enabled using in configuration or in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Please tell me if I am doing anything wrong
Thank you
hi. please help me. i had find lot on net but i dint get solution of my problem.
Problem : in my page their are gride and one dropdownbox when drpdown value change grides records are bind from database. its check with isPostback. its done but when m open gride’s item to edit then i get error of invalid postback or call argument.
according to my surf on net its error becuse i need to register all my dropdown items in server side. its working only selected item on first time when page load. but it dropdown item change then my edit click give me error about invalid postback.
i had tried EnableEventvalidation=”True” i have to make it true. but its not working.
i also used update panel and also try to register all dropdown item by using clientscript. registeronstartup(..myareguments..)
but still m getting same problem.
plse help me
hope i will get solution from u..
thanks in advance.
Ey thanks for the script had also a (mall functioning) script for adding options to a listbox but this one is way better
Grz
Hi Friends,
This code works properly, but I am facing one problem over here.
If I’ve to add the same Option object to another Drop Down
then it throws “Invalid Argument” error.
If I create another Option obj say “Opt2” and add it to another drop down then it works.
Is it possible to use same Option object to add in different drop down?
Anyways, thanks for the code.
Saurabh
🙂
Hi Chirag,
Your solution works good but in order to fetch the selected value in code-behind, is view state the only solution?
I wanted to encapsulate these fields in a user-control but storing values in viewstate means that every new developer using this control should be aware of the viewstate implementation otherwise he/she may waste hours to find out why the selected value is coming as default value.
Thanks in advance
Shilpi
hi frnd’s
i recently get this site & happy to see u solv many problems in different language, so i have also a problem can u help me…
prob…
i create a JSP page (“registration form”) in this i give a “seminar” listbox in this i get values from database (Access), i want wen a one user choose a seminar topic then next time that topic doesn’t display or not highlighted.
plz solve this….
i m very thankful to u
hi chiragrdarji,
plz sen me code for remove items from listbox when it was selected by another person
I’ve spent 2 weeks trying to find something like this. It took less than a minute to get my code working with this function…
Thank you very very much…
hi!! i have a problem
like i want to select objects from the dropdown list and then after selecting, in my web page list of radio button displayed and if i select another option in drop down list aniother list of radio buttons should be displayed
can anyone help me on this
Hi Mavish,
check this out and let me know is it useful to you or not…
on aspx page:
javascript function:
function toggleOnDDL()
{
var val = document.getElementById(“ddlChange”)[document.getElementById(“ddlChange”).selectedIndex].value;
if(val == ‘Select’)
{
document.getElementById(“ForOneInDDL”).style.display=”none”;
document.getElementById(“For1InDDL”).style.display=”none”;
document.getElementById(“ForTwoInDDL”).style.display=”none”;
document.getElementById(“For2InDDL”).style.display=”none”;
document.getElementById(“labelOne”).style.display=”none”;
document.getElementById(“label1″).style.display=”none”;
document.getElementById(“labelTwo”).style.display=”none”;
document.getElementById(“label2″).style.display=”none”;
}
else if(val == ‘Two’)
{
document.getElementById(“ForOneInDDL”).style.display=”none”;
document.getElementById(“For1InDDL”).style.display=”none”;
document.getElementById(“ForTwoInDDL”).style.display=”block”;
document.getElementById(“For2InDDL”).style.display=”block”;
document.getElementById(“labelOne”).style.display=”none”;
document.getElementById(“label1″).style.display=”none”;
document.getElementById(“labelTwo”).style.display=”block”;
document.getElementById(“label2″).style.display=”block”;
}
else if(val == ‘One’)
{
document.getElementById(“ForOneInDDL”).style.display=”block”;
document.getElementById(“For1InDDL”).style.display=”block”;
document.getElementById(“ForTwoInDDL”).style.display=”none”;
document.getElementById(“For2InDDL”).style.display=”none”;
document.getElementById(“labelOne”).style.display=”block”;
document.getElementById(“label1″).style.display=”block”;
document.getElementById(“labelTwo”).style.display=”none”;
document.getElementById(“label2″).style.display=”none”;
}
}
thanks dear…thank you very much..:)
Hello All,
Can you Tell me how to check value is selected in listbox control using Javascript (before page post Back) in asp.net ?
no comments…
( i am not a politician by the way..0
Correct me if Im wrong here , as I am by no means a programmer , developer or anything to the effect , just a ‘ newbie’ to everything – but I believe ( in my humble opinion – and I may be wrong here , so please do forgive me if I am ) ; however , isnt the ‘end tag’ in the script tag in the wrong place ? at the moment , your script tag is like so : ; whereas I believe it should be as such : No??? I am just curious , for as I have just mentioned , I know nothing about javascript or coding , but this just caught my attention .
Thank you & smile , Mootools & JQuery Love you 🙂
[…] question i find this solution at Add items in Drop Down List or List Box using Javascript Tech Treasure PHP Code: function AddItem(Text,Value) { […]
Does anyone know how to work with items in a listbox that contain apostrophes as in the following example?
lstDocumentation.AddItem(“User’s Guide“);
Thanks a lot………….
PROBLEM: external script can’t modify selectbox on the fly
HTML source:
Code:
…
None
…
function getOptions() {
parent.secret.location.href=’externalGetoptions.js’;
}
externalGetOptions.js
Code:
document.formA.selectA.options[document.formA.selectA.options.length]=new Option(“Example1”, “Example1 value”, false, false);
The script in externalGetOptions is basically ok (as I call it directly in the html source (when I place the code in the script section in the HTML-source) everything works fine). Point is that this piece of script in the HTML source is built on the server side and need to be in an external js-file. So it needs to be an onclick event.
Message I get:
document.formA is undefined.
I assume he can’t find the select element
sorry about the last post, it wasnt complete.
in the html source there is a form with a select box. the selectbox includes an onclick event which fires the getOptions function
Gooood.. Thanks..
Thanks..
In your reply to Purnima below you have mentioned “You can call this function on “onchange” event of dropdownlist.”
WHICH FUNCTION??? I need it urgently… Thnaks.
Purnima,
Nice question. Let me explain you, when you fill the items in dropdown list using code behind your valus are stored in viewstate and during postback server loads these values from viewstate and you will get the selected value and selected index.
Now when you add a new item in dropdownlist using javascript this value is added from client side and thus will not stored in viewstate so server is not aware of (or have no idea) about new item. So during postback you will not get this value.
To get the selected value on code behind you need to store selected item from dropdownlist in to a hidden field before postback. You can either do it by calling a javascript function on “OnClientClick” event (or by registring javascript function in code behind using Button.Attributes.Add(”onclick”,”javascript function name”);) which get the selected value from dropdown and save it in hidden field.
document.getElementById(”Hidden Field Client ID”).value = document.getElementById(”Dropdownlist client ID”).options[document.getElementById(“Dropdownlist client ID”).selectedIndex].text;
OR
You can call this function on “onchange” event of dropdownlist.
I hope this has cleared you doubt and will help in solving your isue.
i am adding items to List using javascript successfully.
But.
after post back these items get disappear, means ListBox not keeping its state after post back when addding items using javascrpt.
Kindly give me solution for that.
Hi,
Please help. Code is working in IE 8, but not in FF 3.5 or Google Chrome or netscape.
I am trying to update parent window select box from child window
my code is :
var y = window.opener.document.createElement(“option”);
y.text = ‘hitesh’;
y.value = ‘hitesh’;
var x=window.opener.document.getElementById(“js_id2”);
x.options.add(y);
Please reply asap, it is urgent !
Hi,
Please help. Code is working in IE 8, but not in FF 3.5 or Google Chrome or netscape.
I am trying to update parent window select box from child window
my code is :
var y = window.opener.document.createElement(”option”);
y.text = ‘hitesh’;
y.value = ‘hitesh’;
var x=window.opener.document.getElementById(”js_id2″);
x.options.add(y);
Please reply asap, it is urgent !
Thanks
Hitesh
Thank you very much guys for this code
gracias por tu consejo me ayudo mucho.
thanks for your help because it work to me.
see you!
Thanks for the code.. It was useful. I am trying to add 30 options to the drop down list using a loop arnd your code. However I must specify one of the options as the default selected option. Can u tell me how to do this.???
Imperfective distinction includes Count vs. ,
Hello,
I am able to add the items to the dropdown using the javascript but my problem is that In my code behind page(vb.net) all the time dropdown selected index is hold 0. how I can get the actual selected value.
Please give the answer.
Regards,
Ravi
Very nice.
thank You
Hey i have requriement.
I have 2 dropdownlist . In first dropdown i have to select multiple selections.But i need to make a ajax call.how to pass selected values
Cool Mate 🙂
plz send me the code how to transfer multiple selected items from one listbox to another list box using javascript in php
var opt = document.createElement(“option”);
document.getElementById(“RadioButtonList1”).options.add(opt)
opt.text = “Four”;
opt.value = “4”;
above script not working ?
How to add new listitem in radiobutton list?
I have one drop down list how to display dates in descending order
After postback dropdownlist will lose items.
Hi. Chirag Darji.
I am new to jsp and java script.
I want to create jsp registration page with three dropdown of country, state and city.
State dropdown will be filled according the value of country and city will be filled according to value of state.
Please rpl on my mail.
Thanks.
This code is very much helpful for me.
but,
i am trying to make my selection another one after selecting first one, then the values in the dropdown is added in the previews list.
whether it should be replace the first list.
How can it be done.
help!!!!
function addOption_list()
{
var month = new Array(“January”,”February”,”March”,”April”,”May”,”June”,”July”,”August”,”September”,”October”,”November”,”December”);
for (var i=0; i < month.length;++i){
document.getElementById("dds").options[i] = new Option(month[i],month[i]);
}
how to get this type of dropdown value in asp.net
Hi all,
I want to add textbox box details to asp.net treeview using javascript.
How is it posiible,.
but unable to work in spring.net
var size_array = result.split(“#”);
var num = size_array.length – 1;
for (var i = 0; i < num; i++) {
if (size_array[i] != "") {
var opt1 = document.createElement("option");
// Add an Option object to Drop Down/List Box
document.getElementById("folderList").options.add(opt1);
// Assign text and value to Option object
opt1.text = size_array[i];
opt1.value = size_array[i];
}
}
code sets value to DDL but unable to get selectedindex. it always shows selected index 0 for any selected item in ddl
Hi all
i creat pages using html. but i want to add user name and password, then store smoewhere(table,listboxes,any elements) in html. when the user want loging this,it cheks user name and pasword.
Is it possible doing this using html and javascript?. if so pls send me a code eryone.
(this implies how to add data in to elements and accessing the stored data )
NB this is done in the client side(with out using the database)
thank U eery one!!!
Hi all
i creat pages using html. but i want to add user name and password, then store smoewhere(table,listboxes,any elements) in html. when the user want loging this,it cheks user name and pasword.
Is it possible doing this using html and javascript?. if so pls send me a code eryone.
(this implies how to add data in to elements and accessing the stored data )
NB this is done in the client side(with out using the database)
thank U eery one!!!
Hi…. To Everyone
Hi…..
Could anyone tell me if this is restricted only for below mentioned techs. As I am asking about PHP, Mysql, and other opensource techs.
Articles of ASP.NET, C#, SQL Server, Timesaver Tools
Thanks in advance…..
is really so superb and easy idea and code from your side
so thanks……….
Hi,
How can I make the added option to be saved and used in server side?
I am a AspNet developer.
Chirag, Your code really helped me today.. I was trying to find a solution to add a value in listbox and it was only working in IE.. Firefox/Chrome it was failing.. Your code made it work.
so Thank you. you have created terrific blog with so much info in it.
BTW, I see your picture was taken during Utarayan (Kite festival).. Is it Ahmedabad?
Cheers!
Nikhil
Nikhil,
Thank you for motovational lines.
Yes it was taken during Uttarayan and its Ahmedabad.
Very very thank u . i forgot this method & got mad for two hours. thank u thank u
i want select car model no in dropdownlistbox2 to corespondin dropdownlistbox one.
for example, if i select maruti in dropdownlistbox1 then corespondi show all model no of maruti in drpdownlistbox2,
ex:- maruti 3i,maruti 800,maruti 900, some thing etc.
Works well, thank you!
i am working on share point . i have appended value to dropdownlist through Jquery but when i intiate server cal with selecting newly added value then server will through an error please help me out to resolve this issue
code
var value=”p”;
$(controlName).append($(“”).val(value).html(value));
i have small dought ,i have to fill some data from database to dropdownlist,then now i want to change the order of dropdown list values send me the code for the tone
how to add array in dropdownlist?
I have a doubt about this in javascript
Computers :
Select One
Desktop
Laptop
Brand :
in this form I have two dropdown boxes. In the first box I have two options.
I want to change value of another dropdown box as I click option of first dropdown box….
e.g.
If I select Desktop option from the first dropdown box then brand list should be display in other dropdown box (using javascript)
plz help me…..
I have a doubt about this in javascript
” Computers :
Select One
Desktop
Laptop
”
in this form I have two dropdown boxes. In the first box I have two options.
I want to change value of another dropdown box as I click option of first dropdown box….
e.g.
If I select Desktop option from the first dropdown box then brand list should be display in other dropdown box (using javascript)
plz help me…..
Thank u very much for the Post
thanks
Hi, could you suggest on how to create this option as the first element in the list box. It is creating as the last option.
don’t worry, I figured it out.
Hi Chirag
Your code is very good it solved half of m problem. My problem is I am using a for loop to add more options to the select control but i keep overwriting the option’s value and text and only the last option can be seen. Plz help.Thanks
Hello friend this is not working for me at all
keep try It will work
My problem is i am getting text from excel sheet in drop down but when i select text from drop down its value should be pass.
How to add two textbox values and displaying the result in ddl and saved in ddl? (In javascript)
i’m trying but it dose not work. please help me
Thank you. iI works fine. Thank you for the code.
Hi this solved my great headache. I was using the following before.
document.getElementById(“DropDownList”).add(opt);
Your code works for me. ( i am using FF 3.6 – for some reason )..
Great
it’s working but when i try to get value of
DropDown.SelectedItem.Value;
it gives me empty value please help me..
That didn’t work for me but the following did,
var dropdownObj = document.getElementById(“dropdown”);
dropdownObj.options[dropdownObj.options.length]=new Option(text,val);
i need code for drag and drop listview item to another control (may be to listbox or imagebutton control) . if possible please i need javascript for it.
I do trust all the concepts you have presented for your post. They’re very convincing and can certainly work. Still, the posts are very quick for beginners. May you please extend them a little from subsequent time? Thank you for the post.
Thanks a lot
We absolutely love your blog and find a lot of your post’s to be just what I’m looking for.
Does one offer guest writers to write content in your case?
I wouldn’t mind publishing a post or elaborating on some of the subjects you write with regards to here. Again, awesome weblog!
thank you
Perfect solution, when jQuery .append() not works with Google Crome.
Thanks a lot…
🙂
Using this code I got the following error message:
‘undefined’ is null or not an object
I am using IE 8.
Thanks.
Using this code I got the following error message:
‘undefined’ is null or not an object
I am using IE 8. Can you help me?
Thanks.
Sorry. Iam using not IE 8 but IE 7.
Using this code I got the following error message:
‘undefined’ is null or not an object
Does anyone know what’s the problem?
Thanks.
hey there and thank you for your info – I have definitely picked up something new from right here.
I did however expertise a few technical issues using this web site,
as I experienced to reload the web site many times previous to I could get it to load correctly.
I had been wondering if your hosting is OK? Not that I’m
complaining, but sluggish loading instances times will very
frequently affect your placement in google and
can damage your high-quality score if advertising and marketing with Adwords.
Anyway I am adding this RSS to my e-mail and could look
out for much more of your respective intriguing content.
Ensure that you update this again very soon.
In this way, you wiull minimize the chances of loss.
Standing with back to the wall ‘ if he does this he’s likely also
not feeling sociable. The Tigers have to bbe tougher in the trenches, and ruun the bball effectively.
Дорогие друзья приглашаю Вас на сервер Lineage 2
Сервер в старых добрых традициях. Делалось все для честной и интересной игры.
На самом деле очень хороший проект с душевной атмосферой.
Полное описание всех особенностей можно увидеть на нашем сайте.
Сайт сервера –> http://l2immortal.com
I think the admin of this site is really working hard for his web site, for the reason that here every stuff is
quality based data.
How to use for-loop in javascript to add elements to the dropdown.
Hi All,
I Bind Drop-down like
var jsdata = JSON.parse(data.d);
$.each(jsdata, function (key, value) {
$(‘#’) .append($(“”).val(value.ID).html(value.Name));
but i am having more that 7000 record to bind and for binding it takes more than 1 min. is any solution for same problem. how to reduce time any other alternate way ..please Help .
Thanks in Advance.
Thanks…i’m fresher for asp.net… i hope this website can help to me… i try this code… it execute well….